import { defineStore } from 'pinia'
import axios from '@/api'
import { ref, reactive, toRefs } from 'vue'
import { storage } from "@/util"


export default defineStore('settings', () => {
    // 获取选择列表
    type Items = Array<{
        label: string,
        value: string
    }>
    const source = {
        dict_education_level: [] as Items,
        dict_monthly_income: [] as Items,
        system_config: undefined as any,
        dict_purpose: [] as Items,
        dict_company_type: [] as Items,
        dict_partner_banks: [] as Items
    }
    let settings = reactive<typeof source & { [key: string]: Items | any }>(source)
    let getSettingInfo = async () => {
        let data = await axios.get<any>('/setting/info')
        for (let i in settings) {
            let settingItem = data.find((item: any) => item.name === i);

            if (settingItem) {
                if (Array.isArray(settingItem.value)) {
                    settings[i] = settingItem.value.map((item: any) => ({ label: item.name, value: item.value }));
                } else {
                    settings[i] = settingItem.value; // 直接赋值非数组类型的值
                }
            }
        }
    }
    getSettingInfo()

    // 获取广告列表
    let home_swipers = ref<any[]>([])
    let other_banners = ref<any>()
    let banner_loading = ref(true)
    let getBanners = async () => {
        let data = await axios.get<any>('/setting/banners')
        home_swipers.value = data.home_swiper
        delete data.home_swiper
        other_banners.value = data
        banner_loading.value = false
    }
    getBanners()
    // 获取省市区
    let regions = ref<Array<any>>([]), currentRegion = ref<string>('广州市')
    let getRegions = async () => {
        if (regions.value.length) return regions.value;
        let data = await axios.get<Array<any>>('/setting/regions')
        let dataFilter = (data: Array<any>) => {
            data.forEach((item, idx) => {
                data[idx] = {
                    label: item.name,
                    value: item.id
                }
                item.children ? data[idx].children = dataFilter(item.children) : null;
            })
            return data
        }
        regions.value = dataFilter(data)
        return regions.value
    }
    return {
        ...toRefs(settings),
        getRegions,
        other_banners,
        home_swipers,
        banner_loading,
        getSettingInfo,
        currentRegion
    }
},
    {
        persist: {
            storage,
            paths: ['currentRegion'],
        }
    })

